﻿using Grpc.Net.Client;
using Nacos.V2;

public static class GrpcNacosExtensions
{
    public static GrpcChannel CreateGrpcChannel(string ip, int port, string scheme = "https", bool ignoreCertificate = true)
    {
        var STR = string.Format("{0}://{1}:{2}/", scheme, ip, port);
        Console.WriteLine(string.Format("==================target server is {0}==================", STR));
        if (ignoreCertificate)
        {
            return GrpcChannel.ForAddress(STR, new GrpcChannelOptions
            {
                HttpHandler = new HttpClientHandler
                {
                    // Return `true` to allow certificates that are untrusted/invalid
                    ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                }
            });
        }
        else
        {
            return GrpcChannel.ForAddress(STR);
        }
    }
    public static async Task<GrpcChannel?> GetGrpcChannel(this INacosNamingService nacosNamingService, string serviceName, string scheme = "https", bool ignoreCertificate = true)
    {
        var instances = await nacosNamingService.SelectOneHealthyInstance(serviceName);
        if (instances != null)
        {
            return CreateGrpcChannel(instances.Ip, instances.Port, scheme, ignoreCertificate);
        }
        return null;
    }
}